package com.zhiyuancode.mqack.message.base.message;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * @author 杨志远
 * email faryangsh@163.com
 * Date    2018-05-02
 */
public abstract class BaseMessage implements Message {
    /**
     * JSON-Object转换
     */
    protected static final ObjectMapper OBJECT_MAPPER;

    static {
        OBJECT_MAPPER = new ObjectMapper();

        // 忽略不能反序列化的字段
        OBJECT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        // Java日期时间格式
        //OBJECT_MAPPER.registerModule(new JavaTimeModule());
        //OBJECT_MAPPER.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        // JSON文本缩进
        //OBJECT_MAPPER.enable(SerializationFeature.INDENT_OUTPUT);
    }

    @JsonInclude(value = JsonInclude.Include.NON_EMPTY)
    private String msgId;

    @Override
    public String acquireMsgId() {
        return msgId;
    }

    public BaseMessage(String msgId) {
        this.msgId = msgId;
    }

    public void setMsgId(String msgId) {
        this.msgId = msgId;
    }

    public BaseMessage() {
    }

    /**
     * Object -> JSON
     *
     * @return JSON
     */
    public String toJson() {
        try {
            return OBJECT_MAPPER.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * JSON -> Object
     *
     * @return Object
     */
    public static <T extends BaseMessage> T toObject(String jsonStr, Class<T> valueType) throws IOException {
        return OBJECT_MAPPER.readValue(jsonStr, valueType);
    }

    public String acquireMqAddress() {
        throw new RuntimeException("该方法没有被重写");
    }
}
